package com.yej.aiPolice.presenter

import android.util.Log
import com.yej.aiPolice.model.beans.ResponseInfo
import com.yej.aiPolice.model.net.NetService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

 open abstract class NetPresenter {
    val service: NetService

    init {

        /*
           **打印retrofit信息部分
            */
        val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger (){ message ->
            //打印retrofit日志
            Log.e("RetrofitLog", "retrofitBack = $message")
        })
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val client = OkHttpClient.Builder() //okhttp设置部分，此处还可再设置网络参数
            .addInterceptor(loggingInterceptor)
            .build()


        val retrofit = Retrofit.Builder()
            .baseUrl("http://121.43.232.225/")
            .addConverterFactory(GsonConverterFactory.create()).client(client)
            .build()

        service = retrofit.create<NetService>( NetService::class.java!!)
    }

    val callBack = object : Callback<ResponseInfo> {

        override fun onResponse(call: Call<ResponseInfo>?, response: Response<ResponseInfo>?) {
            if(response == null){
                Log.e("网络请求","没有成功返回")
            }
            else if(response.isSuccessful){
//                    Log.e("hone",)
                val responseInfo = response.body()
                if(responseInfo.code.equals("200")){
                        var json = responseInfo.data
                        parserJson(json)
                }else{
                    Log.e("网络请求","错误码:${responseInfo.code}")
                    //其他错误
                }
            }else{
                Log.e("网络请求","服务器代码出错")
            }
        }

        override fun onFailure(call: Call<ResponseInfo>?, t: Throwable?) {
            //没有连接上服务器
            Log.e("网络请求","没有连接上服务器")
        }
    }

    abstract fun parserJson(json: String?) ;
}